﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BeanboxSoftware.BeanMapTest
{
  public static class TestUtils
  {
    public static void AssertExceptionThrown<T>(Action action) where T : Exception
    {
      AssertExceptionThrown<T>(action, "Exception type thrown by action");
    }
    public static void AssertExceptionThrown<T>(Action action, string message) where T : Exception
    {
      var actualType = typeof(void);

      try
      {
        action();
      }
      catch (Exception ex)
      {
        actualType = ex.GetType();
        if (!Inherits(actualType, typeof(T)))
        {
          throw;
        }

        return;
      }

      if (!Inherits(actualType, typeof(T)))
      {
        throw new InvalidCastException(message);
      }
    }

    private static bool Inherits(Type child, Type target)
    {
      if (child == null)
      {
        return false;
      }

      if (child == target)
      {
        return true;
      }

      return Inherits(child.BaseType, target);
    }
  }
}
